package pers.chao.tool.infrastructure.resource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.url.UrlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * Description: io操作
 *
 * @author W.Chao
 * @date 2020/11/15 0:27
 **/
public final class IosUtil {
	private static final Logger logger = LoggerFactory.getLogger(IosUtil.class);

	private IosUtil() {
	}

	public static long copy(String from, String to) {
		BufferedInputStream in = FileUtil.getInputStream(from);
		BufferedOutputStream out = FileUtil.getOutputStream(to);
		return IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
	}

	public static long copy(String from, String to, int bufferSize) {
		BufferedInputStream in = FileUtil.getInputStream(from);
		BufferedOutputStream out = FileUtil.getOutputStream(to);
		return IoUtil.copy(in, out, bufferSize);
	}

	public static long copy(InputStream in, String to) {
		BufferedOutputStream out = FileUtil.getOutputStream(to);
		return IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
	}

	public static long copy(InputStream in, File file) {
		BufferedOutputStream out = FileUtil.getOutputStream(file);
		return IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
	}

	public static BufferedReader getBufferedReader(InputStream stream) {
		return IoUtil.getReader(stream, StandardCharsets.UTF_8);
	}

	public static OutputStreamWriter getBufferedReader(OutputStream stream) {
		return IoUtil.getWriter(stream, StandardCharsets.UTF_8);
	}

	public static BufferedReader getBufferedReader(String url) {
		URL toURL = UrlBuilder.ofHttp(url, StandardCharsets.UTF_8).toURL();
		return getBufferedReader(toURL);
	}

	public static BufferedReader getBufferedReader(URL url) {
		return getBufferedReader(getNetInputStream(url));
	}

	public static InputStream getNetInputStream(URL url) {
		InputStream in = null;
		try {
			URLConnection urlConnection = url.openConnection();
			in = urlConnection.getInputStream();
		} catch (IOException e) {
			logger.warn("URL open connection occur error: {}", e.getMessage());
		}
		return in;
	}


}
